package top.lanscarlos.ashcraft.repository;

import com.sun.istack.NotNull;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Repository;
import top.lanscarlos.ashcraft.pojo.LogInfo;
import top.lanscarlos.ashcraft.pojo.Seller;
import top.lanscarlos.ashcraft.pojo.User;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;

/**
 * Ashcraft
 * top.lanscarlos.ashcraft.repository
 *
 * @author Lanscarlos
 * @since 2022-05-25 16:01
 */
@Repository
public class LogRepository {
    @Autowired
    private SessionFactory sessionFactory;

    /**
     * 获取登录对象
     *
     * @return 若成功匹配则返回用户或商家 反之 null
     * */
    @Nullable
    public Object findLogInstance(
            @NotNull String phone,
            @NotNull String password
    ) {
        Object object = null;
        Session session = sessionFactory.openSession();
        Transaction transaction = session.beginTransaction();
        try {
            // 获取 criteria 构建器
            CriteriaBuilder builder = session.getCriteriaBuilder();
            // 获取查询工具对象，并指定返回的结果类型
            CriteriaQuery<LogInfo> criteria = builder.createQuery(LogInfo.class);
            // 获取 LogInfo 数据表相关对象
            Root<LogInfo> root = criteria.from(LogInfo.class);

            // 指定查询的数据表
            criteria.select(root);
            // 添加条件 where log_info.phone = phone
            criteria.where(builder.and(builder.equal(root.get("phone"), phone), builder.equal(root.get("password"), password)));
//            criteria.where(builder.equal(root.get("phone"), phone));
//            criteria.where(builder.equal(root.get("password"), password));

            // 获取单个结果
            LogInfo info = session.createQuery(criteria).getSingleResult();
            if (info == null) return null;

            String[] identity = info.getIdentity().split("@");
            // 无效标识符 删除数据
            if (identity.length != 2) {
                session.delete(info);
                transaction.commit();
                return null;
            }

            int id = Integer.parseInt(identity[1]);
            switch (identity[0]) {
                case "user":
                    return session.get(User.class, id);
                case "seller":
                    return session.get(Seller.class, id);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            session.close();
        }
        return object;
    }
}
